package site.anxuan.seckill.validator;

import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class ObjectValidator {

    private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public Map<String, String> validate(Object obj) {
        if (obj == null) return null;
        Map<String, String> result = new HashMap<>();
        Set<ConstraintViolation<Object>> set = validator.validate(obj);
        for (ConstraintViolation<Object> cv : set) {
            result.put(cv.getPropertyPath().toString(), cv.getMessage());
        }
        return result.size() == 0 ? null : result;
    }

}
